package com.sykj.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sykj.entity.OrderMaster;
import com.sykj.service.IOrderMasterService;
import com.sykj.service.IProductInfoService;
import com.sykj.util.HttpClientUtils;
import com.sykj.util.WeChatUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;

/**
 * @ClassName WeChatCallBack
 * @Description TODO 接收微信回调接口
 * @Author vains
 * @Date 2019/6/30 18:18
 * @Version 1.0
 **/
@Controller
public class WeChatCallBack {

    @Autowired
    private WeChatUtils weChatUtils;

    @Autowired
    private IOrderMasterService masterService;

    @Autowired
    private IProductInfoService infoService;

    /**
     * 支付成功状态码
     **/
    private static final String SUCCESS_CODE = "0";

    private static final String STATUS = "status";

    private static final String RESULT_CODE = "result_code";

    /**
     * 处理支付成功之后回调通知
     * @Author vains
     * @Date 2019/7/1 15:21
     * @param request
     * @param response
     * @return void
     **/
    @RequestMapping("/notifyUrl")
    public void notifyUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 解析request中的xml
        Map<String, String> data = WeChatUtils.parseRequest(request);
        // 获取对应订单信息
        OrderMaster master = masterService.getById(data.get("out_trade_no"));
        // 改变支付状态为已支付
        master.setPayStatus(1);
        masterService.updateById(master);
        // 给用户发送一个提示信息，提示用户订单支付成功
        weChatUtils.sendOrderByTemplate(master.getOrderId());
        response.getWriter().println("success");
    }

    /**
     * 支付前登录回调， 登录成功之后修改订单内购买人openid
     * 成功之后发起微信支付
     * @Author vains
     * @Date 2019/7/1 0:18
     * @param code 微信访问时携带的票据
     * @param state 微信访问时携带的state，登录之前这里传入的是orderId
     *              请求登录url中state是什么，这个就是什么
     * @param response 重定向
     * @return void
     **/
    @RequestMapping("/loginCallBack")
    public void loginCallBack(String code, String state, HttpServletResponse response) throws IOException {
        System.out.println(code+"------>>>"+state);
        // 请求获取openid
        String info = HttpClientUtils.doGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + HttpClientUtils.APPID + "&secret=" + HttpClientUtils.APPSECRET + "&code=" + code + "&grant_type=authorization_code");
        ObjectMapper mapper = new ObjectMapper();
        // 将返回的json转为map
        Map map = mapper.readValue(info, Map.class);
        String openid = (String) map.get("openid");
        // 获取不到openid提示前端
        if (StringUtils.isBlank(openid)) {
            response.sendRedirect("http://vains.easy.echosite.cn/#/createOrder?error=loginError");
            return;
        }
        // 修改数据库订单表中购买人openid
        OrderMaster master = masterService.getById(state);
        master.setBuyerOpenid(openid);
        masterService.updateById(master);
        // 发起微信支付
        Map<String, String> stringMap = WeChatUtils.wxPay("阿香点餐", String.valueOf(master.getOrderAmount().multiply(new BigDecimal(100)).toBigIntegerExact()), state);
        if (SUCCESS_CODE.equals(stringMap.get(STATUS)) && SUCCESS_CODE.equals(stringMap.get(RESULT_CODE))) {
            response.sendRedirect("https://pay.swiftpass.cn/pay/jspay?token_id="+stringMap.get("token_id")+"&showwxtitle=1");
            return;
        }
        response.sendRedirect("http://vains.easy.echosite.cn/#/createOrder?error=payError");
    }

    @RequestMapping("/pcLoginCallBack")
    public String pcLoginCallBack(String code, String state, HttpServletResponse response) throws IOException {
        System.out.println(state + "#/index");
        return "redirect:" + state + "#/index";
    }

}
